package part17;

import java.lang.reflect.Constructor;
import java.util.HashMap;
import java.util.Random;

/**
 * @author wcj
 * @Date 2021/6/1 21:15
 * @Version 1.0
 */
public class Part1714 {

    public static <T extends GroundLog> void detectSpring(Class<T> type) throws Exception {
        Constructor<T> constructor = type.getConstructor(int.class);
        HashMap<GroundLog, Prediction> map = new HashMap<>();
        for (int i = 0; i < 10; i++) {
            map.put(constructor.newInstance(i), new Prediction());
        }
        System.out.println("map:" + map);
        GroundLog t = constructor.newInstance(3);
        System.out.println("GroundLog:" + t);
        if (map.containsKey(t)) {
            System.out.println(map.get(t));
        } else {
            System.out.println("not found:" + t);
        }
    }

    public static void main(String[] args) throws Exception {
        detectSpring(GroundLog.class);
    }
}

/**
 * 使用自己的类作为HashMap的键的时候，一定要实现equals()方法和hashCode()方法
 * 如果不实现，默认使用Object的equals方法，比较的是两个对象的地址
 */
class GroundLog {
    private int number;

    public GroundLog(int n) {
        this.number = n;
    }

    @Override
    public String toString() {
        return "GroundLog #" + number;
    }

    @Override
    public int hashCode() {
        return number;
    }

    @Override
    public boolean equals(Object obj) {
        return obj instanceof GroundLog && number == ((GroundLog) obj).number;
    }
}

class Prediction {
    public static Random random = new Random(47);
    public boolean shadow = random.nextDouble() > 0.5;

    @Override
    public String toString() {
        if (shadow) {
            return "Summer";
        } else {
            return "Spring";
        }
    }
}